package com.reborn.first.initiator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

import com.reborn.first.acceptor.MessageFactory5SP2;

import cn.hutool.core.thread.ThreadUtil;
import jodd.props.Props;
import quickfix.Application;
import quickfix.ConfigError;
import quickfix.FieldNotFound;
import quickfix.FileLogFactory;
import quickfix.FileStoreFactory;
import quickfix.Initiator;
import quickfix.InvalidMessage;
import quickfix.LogFactory;
import quickfix.Message;
import quickfix.MessageFactory;
import quickfix.MessageStoreFactory;
import quickfix.Session;
import quickfix.SessionID;
import quickfix.SessionNotFound;
import quickfix.SessionSettings;
import quickfix.SocketInitiator;
import zb.fix.client.data.TradingRequest;

/**
 * Created by xuqian_sx on 2017-7-27.
 */
public class MyInitiator {
	private final static Logger log = Logger.getLogger(MyInitiator.class);
	private boolean initiatorStarted = false;
	public static Initiator initiator = null;

	public MyInitiator(SessionSettings sessionSettings) throws ConfigError, IOException {
		Application application = new MyInitiatorApplication();
		MessageStoreFactory messageStoreFactory = new FileStoreFactory(sessionSettings);
		LogFactory logFactory = new FileLogFactory(sessionSettings);
		MessageFactory messageFactory = new MessageFactory5SP2();
		initiator = new SocketInitiator(application, messageStoreFactory, sessionSettings, logFactory, messageFactory);

	}

	public static InputStream getSettingsInputStream(String[] args) throws FileNotFoundException {
		InputStream inputStream = null;
		if (args.length == 0) {
			inputStream = MyInitiator.class.getClassLoader().getResourceAsStream("initiator.cfg");
		} else if (args.length == 1) {
			inputStream = new FileInputStream(args[0]);
		}
		if (inputStream == null) {
			System.out.println("configfile not found");
			System.exit(1);
		}
		return inputStream;
	}

	public synchronized void logon() {
		if (!initiatorStarted) {
			try {
				initiator.start();
				initiatorStarted = true;
			} catch (Exception e) {
				log.error("Logon failed", e);
			}
		} else {
			for (SessionID sessionId : initiator.getSessions()) {
				Session.lookupSession(sessionId).logon();
			}
		}
	}

	

}
